<template>
  <view class="">
    <view class="sv-exam-plus-page">
      <sv-exam-plus :type="examOptions && examOptions.opt.type" :lib="examOptions && examOptions.param.from_lib"
        :data="examData" :examPaperId="examPaperId" :favs="myFavs" @changePaper="changePaper" @quit="onQuit"></sv-exam-plus>
    </view>
  </view>
</template>

<script>
  import {
    shuffleAndPick
  } from '@/uni_modules/sv-exam-plus/utils/index.js'
  import store from '@/uni_modules/sv-exam-plus/store/index.js'
  import {
    updateRecitePaperAPI,
    submitAPI
  } from '@/api/addPaper/addpaper.js'
  export default {
    data() {
      return {
        completedQuestionIds: [],
        examOptions: null,
        examData: [], // 题目列表
        myFavs: [], // 收藏夹
        navigationBarTitleText: '考试',
        chucuolv: '',
        examPaperId: '',
        progressRecordId: "",
        questionBankType: '',
        answerItems: [],
        associated: false,
      }
    },
    computed: {
      pageTitle() {
        return this.examOptions?.opt.lib_name || '试题'
      },
      total() {
        return store.state.examData.length
      },
      examIndex: {
        set(newIndex) {
          store.commit('updateIndex', newIndex)
        },
        get() {
          return store.state.examIndex
        }
      },
    },
    onLoad() {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.once('e-transmit-exams', async (res) => {
        this.examOptions = res // 从错题本或试题收藏夹页面传过来试题列表      
        // this.init() // 初始化操作
        // 异步获取数据 需要async/await 确保数据取到后再执行后续操作
        await this.handleData()
        if (this.examOptions.opt.questionCompletedCount === 0 || this.questionBankType === 5) {
          uni.$emit('sv-exam-start', 0)
          // const  indexCount =   uni.getStorageSync('sv-exam')
          // indexCount.questionItems.
        }
        // todoContinue需要确保在handleData处理完题库数据装载完成后再执行
        // this.todoContinue()
        // 开启相关事件监听
        this.examWatcher()

      })
    },
    onUnload() {
      console.log('=== 页面卸载 移除所有监听 ===')
      // 移除事件监听 建议在此处将考试相关所有监听统一移除
      uni.$off('e-exam-paper-item-submit')
      uni.$off('e-exam-paper-complete')
      uni.$off('e-exam-paper-item-fav')
      uni.$off('e-exam-paper-item-feedback')
      const currentQuestionId = store.state.examData[this.examIndex]
      console.log(this.examIndex,'this.examIndex');
      console.log(currentQuestionId.questionId,'currentQuestionId');
      if (this.examOptions.opt.type === 'practice') {
        const data = {
          examPaperId: this.examPaperId,
          doTime: 300,
          answerItems: this.answerItems,
          categoryId: this.categoryId,
          deletedWrong: this.deletedWrong,
          questionBankType: this.questionBankType
        }
        submitAPI(data).then((res) => {
      
        })
      }
      if (this.examOptions.opt.type === 'recite' || this.examOptions.opt.type === 'practice') {
        console.log(this.questionBankType, 'wsm ');
        if (this.questionBankType === 3 || this.questionBankType === 5 || this.questionBankType === 11 || this
          .questionBankType === 12) return

        const param = {
          questionBankType: this.questionBankType,
          id: this.progressRecordId,
          examPaperId: this.examPaperId,
          questionCount: this.total,
          questionCompletedCount: this.examIndex,
          currentQuestionId: currentQuestionId.questionId,
          completedQuestionIds: this.completedQuestionIds,
          doTime: 300
        }
        updateRecitePaperAPI(param).then((res) => {})


      }

    },
    methods: {
      backIndex() {
        uni.navigateback();
      },
      init() {

      },
      // 数据处理
      async handleData() {
        const {
          param,
          opt,
          apifunc,
          title,
          typeL
        } = this.examOptions
        // 模拟从接口异步获取题目数据
        // let dataRes = await apifunc.examList(param)

        if (opt.type == 'exam') {
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: '考试',
          })
          this.examData = tempExamData
        }

        if (opt.type == 'changkao') {
          const param = {
            categoryId: 1,
            questionBankName: '极速背题'
          }
          const dataRes = await apifunc.examList(param)
          let tempExamData = dataRes.paperPartItems || []
          tempExamData = shuffleAndPick(dataRes.paperPartItems, 100)
          uni.setNavigationBarTitle({
            title: '常考考点背题',
          })
          this.examData = tempExamData

        }
        if (opt.type == 'gonggu') {
          let dataRes = {}
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: '巩固背题',
          })
          this.examData = tempExamData

        }

        if (opt.type == 'yicuo') {
          let dataRes = {}
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: 'AI易错背题',
          })
          this.examData = tempExamData

        }
        if (opt.type == 'changjing') {
          let dataRes = {}
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: '电网GIS平台应用场景',
          })
          this.examData = tempExamData

        }

        if (opt.type == 'lianxiang') {
          let dataRes = {}
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: '联想背题',
          })
          this.examData = tempExamData[0].questionItems
        }
        if (opt.type == 'recite') {
          const dataRes = apifunc.examList
          this.examPaperId = dataRes.id
          this.progressRecordId = dataRes.progressRecordId
          this.questionBankType = opt.questionBankType
          let tempExamData = dataRes.paperPartItems || []
          tempExamData = shuffleAndPick(dataRes.paperPartItems, 100)
          uni.setNavigationBarTitle({
            title: '极速背题',
          })
          console.log(tempExamData, 'tempExamData');
          this.examData = tempExamData[0].questionItems
        }
        if (opt.type == 'errorList') {
          let dataRes = {}
          let tempExamData = dataRes.data || []
          tempExamData = shuffleAndPick(dataRes.data, 100)
          uni.setNavigationBarTitle({
            title: '错题集',
          })
          this.examData = tempExamData

        }
        if (opt.type == 'practice') {
          const dataRes = apifunc.examList
          this.examPaperId = dataRes.id || opt.id
          store.commit('updateExamPaperId', this.examPaperId)

          this.questionBankType = opt.questionBankType
          this.progressRecordId = dataRes.progressRecordId
          this.deletedWrong = opt.deletedWrong
          this.categoryId = opt.categoryId
          this.associated = opt?.associated
          store.commit('updateAssociated', this.associated)

          let tempExamData = dataRes.paperPartItems.questionItems || []
          tempExamData = shuffleAndPick(dataRes.paperPartItems, 100)
          if (opt.questionBankType === 4) {
            uni.setNavigationBarTitle({
              title: '顺序刷题',
            })
          } else if (opt.questionBankType === 5) {
            uni.setNavigationBarTitle({
              title: '随机刷题',
            })
          } else if (opt.questionBankType === 6) {
            uni.setNavigationBarTitle({
              title: '单选题型刷题',
            })
          } else if (opt.questionBankType === 7) {
            uni.setNavigationBarTitle({
              title: '多选题型刷题',
            })
          } else if (opt.questionBankType === 10) {
            uni.setNavigationBarTitle({
              title: '全部错题刷题',
            })
          } else if (opt.questionBankType === 9) {
            uni.setNavigationBarTitle({
              title: '我的错题刷题',
            })
          } else if (opt.questionBankType === 3) {
            uni.setNavigationBarTitle({
              title: '联想刷题',
            })
          } else if (opt.questionBankType === 9) {
            uni.setNavigationBarTitle({
              title: '极速背题',
            })
          } else if (opt.questionBankType === 1 && opt.changkaoda !== 'changkaoda') {
            uni.setNavigationBarTitle({
              title: '常考刷题',
            })
          } else if (opt.questionBankType === 1 && opt.changkaoda === 'changkaoda') {
            uni.setNavigationBarTitle({
              title: '易错刷题',
            })
          } else if (opt.questionBankType === 11 || opt.questionBankType === 12) {
            uni.setNavigationBarTitle({
              title: '收藏刷题',
            })
          }

          this.examData = tempExamData[0].questionItems

        }
        // 模拟考试模式需要打乱顺序并取随机100道题目(具体数目可由opt传入)
        // if (opt.type == 'exam') {
        //   tempExamData = shuffleAndPick(dataRes.data, 100)
        //   uni.setNavigationBarTitle({
        //     title: '考试',
        //   })
        // }
        // if (opt.type == 'changkao') {
        //   uni.setNavigationBarTitle({
        //     title: '常考考点背题',
        //   })
        // }
        // if (opt.type == 'yicuo') {
        //   uni.setNavigationBarTitle({
        //     title: 'AI易错背题',
        //   })
        // }
        // if (opt.type == 'changjing') {
        //   uni.setNavigationBarTitle({
        //     title: '电网GIS平台应用场景',
        //   })
        // }
        // if (opt.type == 'gonggu') {
        //   uni.setNavigationBarTitle({
        //     title: '巩固背题',
        //   })
        // }


        if (opt.type == 'recently') {
          uni.setNavigationBarTitle({
            title: '最近错题',
          })
        }

        // this.examData = tempExamData
        this.myFavs = uni.getStorageSync('sv-exam-fav') || []
        this.typeL === typeL


      },
      // 继续进度刷题
      // todoContinue() {
      // 初始化操作

      // const {
      //   param,
      //   opt,
      // } = this.examOptions
      // console.log(this.examOptions, 'this.examOptions');
      // if (opt.type !== 'recite') return
      // // let dataCache = uni.getStorageSync('sv-exam-data-cache')
      // // console.log(dataCache[param.from_lib]?.length > 0, 'dataCache[param.from_lib]?.length > 0');
      // console.log(opt.questionCompletedCount, 'questionCompletedCount');
      // if (opt.questionCompletedCount > 0) {


      // const data = this.examData[opt.questionCompletedCount]
      // console.log(data, 'data');
      // const index = this.examOptions?.opt.questionCompletedCount
      // console.log(index, 'indexxxxx');
      // this.$emit('update:paper', {
      //   data,
      //   index
      // })

      // uni.$emit('sv-exam-start', this.examOptions?.opt.questionCompletedCount)
      // uni.showModal({
      //   title: '系统提示',
      //   content: '是否继续上次答题？',
      //   showCancel: true,
      //   success: ({
      //     confirm
      //   }) => {
      //     if (confirm) {
      // this.examData = this.examData[opt.questionCompletedCount];
      //       // console.log(this.examData, ' this.examDatappppppppppppp');
      //     } else {
      //       // 重新开始答题
      // uni.$emit('sv-exam-start', 0)
      //     }
      //   }
      // })
      // }
      // },

      todoContinue() {
        const {
          param,
          opt
        } = this.examOptions
        // if (opt.type !== 'practice') return
        let dataCache = uni.getStorageSync('sv-exam-data-cache1')
        if (dataCache[param.from_lib]?.length > 0) {
          this.examData = dataCache[param.from_lib]
        }
      },
      /**
       * 切换题目
       * @param {Object} e 当前题目
       */
      changePaper(e) {
        // console.log('==== 切换题目 :', e)
      },

      /**
       * 退出考试
       * @param {Object} e 做题记录，可缓存或上传云端，用作下一次打开后继续进度
       */
      onQuit(e) {
        const {
          param,
          opt
        } = this.examOptions
        // 做出区分，只有练习模式的时候，在退出后可以继续答题
        if (opt.type == 'practice' || opt.type == 'recite') {
          const storage = uni.getStorageSync('sv-exam-data-cache1') || {}
          storage[param.from_lib] = e
          uni.setStorageSync('sv-exam-data-cache1', storage)
        }
        // console.log('==== 退出考试 :', e)
      },
      // exam相关事件监听
      examWatcher() {
        /**
         * 监听题目提交
         * @param e 题目记录: 可根据返回的题目记录，自定义选择存入做题记录或错题本
         */
        uni.$on('e-exam-paper-item-submit', (e) => {
          console.log('==== 监听题目提交 e-exam-paper-item-submit :', e)
          console.log(e, '999');
          this.completedQuestionIds.push(e.paper.questionId)
          this.answerItems.push({
            questionId: e.paper.questionId,
            contentArray: e.selected
          })

        })

        /**
         * 监听考完交卷
         * @param e 答题记录列表: 可根据返回的答题记录列表，缓存或上传云端，提示下一次打开是否继续上次答题
         */
        uni.$on('e-exam-paper-complete', (e) => {
          console.log('==== 监听考完交卷 e-exam-paper-complete :', e)
        })

        /**
         * 监听题目收藏
         * @param e 收藏题目数据
         */
        uni.$on('e-exam-paper-item-fav', (e) => {
          const favStorage = uni.getStorageSync('sv-exam-fav') || []
          if (e.isfav) {
            // 添加收藏
            favStorage.push(e.paper.data)
          } else {
            // 移除收藏
            favStorage.splice(
              favStorage.findIndex((item) => item.exam_id === e.paper.data.exam_id),
              1
            )
          }
          uni.setStorageSync('sv-exam-fav', favStorage)
          // 将新的收藏列表更新至myFavs
          this.myFavs = favStorage
          console.log('==== 监听题目收藏 e-exam-paper-item-fav :', e)
        })

        /**
         * 监听纠错反馈
         * @param e 纠错反馈的题目
         */
        uni.$on('e-exam-paper-item-feedback', (e) => {
          console.log('==== 监听纠错反馈 e-exam-paper-item-feedback :', e)
        })
      }
    }
  }
</script>

<style lang="scss">
  .sv-exam-plus-page {
    width: 100%;
    height: calc(100vh - var(--window-top));
  }
</style>